from celery.utils.serialization import jsonify
from elasticsearch import Elasticsearch
from Home.models import *
import traceback
from django.http.response import JsonResponse
from Home.tools.Myredis import r

def insert_data_to_es():
    es = Elasticsearch("http://101.42.31.212:9200/")
    # 清空数据\

    # es.indices.delete(index='user')
    # es.indices.delete(index='coursees')
    maxindex=r.get_str("maxindex") if r.get_str("maxindex") else 0
    print(maxindex)
    courselist=CourseModel.objects.filter(id__gt=maxindex).all()
    print(courselist)
    if(len(courselist)==0):
        return JsonResponse({"message": '无序更行'})
    try:

        for row in courselist:
            print(row.teacher_id)

            # index就是对应的一张表 eg.对应的就是course表
            es.index(index='coursees', body={
                'id': row.id,
                'table_name': 'course',
                'name': row.name,
                'pid':row.pid.id,
                'topid':row.topid,
                'level':row.level,
                'src':row.src,
                'price':row.price,
                'num':row.num,
                'is_recommend':row.is_recommend,
                'is_down':row.is_down,
                'totalJie':row.totalJie,
                'totalTime':row.totalTime,
                'info':row.info,
                'question':row.question,
                'teacher':row.teacher_id,
            })
        print("###")
        r.set_srt("maxindex",courselist.last().id)
    except:
        print("&&&")
        error = traceback.format_exc()
        print("Error: unable to fecth data", error)
        pass
    return JsonResponse({"message":'ok'})

def testaa(request):
    import redis

    # 假设代码也在Docker容器内运行
    redis_host = '101.42.31.212'
    redis_port = 6379

    client = redis.StrictRedis(host=redis_host, port=redis_port, decode_responses=True)
    client.ping()  # 测试连接
    return JsonResponse({"message":'ok'})
